package org.leumasjaffe.security;

import java.util.Random;
import javax.swing.JOptionPane;
/**
 * XORCrypt implements XOR encryption with a password that is converted into a sliding key.
 * Note that this is not cryptographically secure.
 * @author Christian Walker 
 * @version 1
 */
public class XORCrypt {
	public String outputString;

	public XORCrypt(String input, String password) {
		this.outputString = encryptDecrypt(input,password);
	}

	public XORCrypt(String input) {
		this.outputString = encryptDecrypt(input,generateRandomPassword(input.length()));
	}

	public String generateRandomPassword(int length) {
		Random generator = new Random();
		String temp = "";
		int curr = 0;
		while (curr++ < length)
			temp += (char)(generator.nextInt(93)+33);
		JOptionPane.showMessageDialog(null,"The data is encrypted with" +temp);
		return temp;
	}

	public String encryptDecrypt(String input, String password) {
		 int expandedLength = input.length();
		 return encodeDecode(input, (expandedLength <= password.length()) ? password 
				 : expandString(password, expandedLength));
	}

	public String encodeDecode(String input, String expandedPassword) {
		String result = "";
		for (int x = 0; x < input.length(); x++)
			result += (char)(expandedPassword.charAt(x)^input.charAt(x));
		return result;
	}

	public String expandString(String original, int length) {
		String temp = original;
		int len = original.length();
		int i = len;
		while (i < length) {
			temp += (char)(temp.charAt(i++-len)^temp.charAt(len-1));
		}
		return temp;
	}
	
}